#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PandaCoder 版本更新脚本
使用方法: python update-version.py
"""

import re
import sys
import io
from pathlib import Path

# 设置 Windows 控制台输出编码
if sys.platform == 'win32':
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')

def read_properties(file_path):
    """读取 properties 文件，支持多行值"""
    props = {}
    current_key = None
    current_value = []
    
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        
    for i, line in enumerate(lines):
        stripped = line.strip()
        
        # 跳过空行和注释行
        if not stripped or stripped.startswith('#'):
            # 如果当前有正在读取的key，且遇到空行或注释，说明多行值结束
            if current_key and stripped.startswith('#'):
                props[current_key] = '\n'.join(current_value)
                current_key = None
                current_value = []
            continue
        
        # 检查是否是新的 key=value 行
        if '=' in stripped and not stripped.startswith('|'):
            # 保存之前的 key-value
            if current_key:
                props[current_key] = '\n'.join(current_value)
            
            # 开始新的 key-value
            key, value = stripped.split('=', 1)
            current_key = key.strip()
            current_value = [value.strip()]
        elif current_key:
            # 这是多行值的延续行
            current_value.append(stripped)
    
    # 保存最后一个 key-value
    if current_key:
        props[current_key] = '\n'.join(current_value)
    
    return props

def update_version_properties(plugin_version, version_type, release_date, current_features):
    """更新 version.properties 文件"""
    version_file = Path('src/main/resources/version.properties')
    content = f"""# Auto-generated version information
# DO NOT EDIT THIS FILE MANUALLY
# This file is generated by update-version.py script
# To update version, edit gradle.properties file and run: python update-version.py

version={plugin_version}
versionType={version_type}
releaseDate={release_date}
currentFeatures={current_features}
"""
    version_file.write_text(content, encoding='utf-8')
    print(f"✓ 已更新: {version_file}")

def update_readme(plugin_version):
    """更新 README.md 中的版本号徽章"""
    readme_file = Path('README.md')
    if not readme_file.exists():
        print(f"✗ 未找到: {readme_file}")
        return
    
    content = readme_file.read_text(encoding='utf-8')
    new_content = re.sub(
        r'https://img\.shields\.io/badge/Version-[\d.]+',
        f'https://img.shields.io/badge/Version-{plugin_version}',
        content
    )
    readme_file.write_text(new_content, encoding='utf-8')
    print(f"✓ 已更新: {readme_file}")

def main():
    print("=" * 60)
    print("PandaCoder 版本更新工具")
    print("=" * 60)
    print()
    
    # 读取 gradle.properties
    props_file = Path('gradle.properties')
    if not props_file.exists():
        print("错误: 未找到 gradle.properties 文件")
        sys.exit(1)
    
    props = read_properties(props_file)
    plugin_version = props.get('pluginVersion', '')
    version_type = props.get('versionType', '')
    release_date = props.get('releaseDate', '')
    current_features = props.get('currentFeatures', '')
    
    print("当前版本配置:")
    print(f"  版本号: {plugin_version}")
    print(f"  版本类型: {version_type}")
    print(f"  发布日期: {release_date}")
    print(f"  主要功能: {current_features}")
    print()
    
    # 更新文件
    print("正在更新文件...")
    update_version_properties(plugin_version, version_type, release_date, current_features)
    update_readme(plugin_version)
    
    print()
    print("=" * 60)
    print("✓ 版本更新完成！")
    print("=" * 60)
    print()
    print("已更新的文件:")
    print("  1. src/main/resources/version.properties")
    print("  2. README.md")
    print()
    print("下一步操作:")
    print("  1. 运行 gradlew clean build 重新构建项目")
    print(f"  2. 提交更改: git add . && git commit -m 'chore: update version to {plugin_version}'")
    print(f"  3. 创建标签: git tag v{plugin_version}")
    print("  4. 推送远程: git push && git push --tags")
    print()
    print("📝 同步到博客:")
    print("  运行: python sync-to-blog.py")
    print("=" * 60)

if __name__ == '__main__':
    main()

